<template>
    <div class="user-management-container">

        <div class="form">
            <el-input v-model="username" placeholder="请输入用户名进行搜索"  prefix-icon="el-icon-search"
              style="width:200px;margin-right: 10px"></el-input>
            <el-button type="primary" @click="addUser">新增用户</el-button>
        </div>
        <div class="form">
            <el-button type="primary" @click="chaxun()">查询</el-button>
            <el-button type="info" @click="chongzhi()">重置</el-button>
          
        </div>
        <div class="table">
        <el-table :data="userlist" style="width: 100%" border >
            <el-table-column prop="id" label="ID" width="80"></el-table-column>
            <el-table-column prop="username" label="用户名"></el-table-column>
            <el-table-column prop="nickName" label="姓名"></el-table-column>
            <el-table-column prop="phone" label="电话"></el-table-column>
            <el-table-column prop="email" label="邮箱"></el-table-column>
            
            <el-table-column label="操作" width="200">
                <template #default="scope">
                    <el-button type="text" size="small" @click="editUser(scope.row)">编辑</el-button>
                    <el-button type="text" size="small" @click="deleteUser(scope.row)">删除</el-button>
                </template>
            </el-table-column>
        </el-table>
        <el-pagination @size-change="handleSizeChange" @current-change="handleCurrentChange" :current-page="currentPage"
            :page-size="pageSize" background layout="total, sizes, prev, pager, next" :total="total"></el-pagination>

        </div>
        <!-- 新增/编辑用户对话框 -->
        <el-dialog :title="dialogTitle" v-model="dialogVisible" width="30%">
            <el-form :model="form" :rules="rules" ref="formRef" label-width="80px">
                <el-form-item label="用户名" prop="username">
                    <el-input v-model="form.username" placeholder="请输入用户名"></el-input>
                </el-form-item>
                <el-form-item label="姓名" prop="nickName">
                    <el-input v-model="form.nickName" placeholder="请输入姓名"></el-input>
                </el-form-item>
                <el-form-item label="电话" prop="phone">
                    <el-input v-model="form.phone" placeholder="请输入电话"></el-input>
                </el-form-item>
                <el-form-item label="邮箱" prop="email">
                    <el-input v-model="form.email" placeholder="请输入邮箱"></el-input>
                </el-form-item>
               
            </el-form>
            <template #footer>
                <span class="dialog-footer">
                    <el-button @click="dialogVisible = false">取消</el-button>
                    <el-button type="primary" @click="submitForm">确定</el-button>
                </span>
            </template>
        </el-dialog>

    </div>
</template>
<style>
.avatar-uploader-icon{
border: 1px dashed;
}
</style>
<script setup>
import { ref, reactive, toRefs, onMounted } from 'vue';
import { ElMessage, ElMessageBox } from 'element-plus';
import { Plus } from '@element-plus/icons-vue'
import service from '@/utils/request';
const users = ref([
    { id: 1, username: 'user1', name: '张三', phone: '1234567890', email: 'user1@example.com', avatar: 'https://via.placeholder.com/150' },
    { id: 2, username: 'user2', name: '李四', phone: '0987654321', email: 'user2@example.com', avatar: 'https://via.placeholder.com/150' },
    // 更多用户数据...
]);
const username=ref("")
const userlist=ref([]);
const searchQuery = ref('');
const currentPage = ref(1);
const pageSize = ref(10);
const dialogVisible = ref(false);
const dialogTitle = ref('新增用户');
const form = reactive({
    id: null,
    username: '',
    name: '',
    phone: '',
    password:123456,
    email: '',
    avatar: ''
});

const total = ref(0)

onMounted(()=>{
    getlist()
})
const rules = {
    username: [
        { required: true, message: '请输入用户名', trigger: 'blur' }
    ],
    nickName: [
        { required: true, message: '请输入姓名', trigger: 'blur' }
    ],
    phone: [
        { required: true, message: '请输入电话', trigger: 'blur' }
    ],
    email: [
        { required: true, message: '请输入邮箱', trigger: 'blur' },
        { type: 'email', message: '请输入正确的邮箱格式', trigger: 'blur' }
    ]
};

const formRef = ref(null);

const handleSearch = () => {
    currentPage.value = 1; // 搜索时重置当前页
};

const handleSizeChange = (newSize) => {
    pageSize.value = newSize;
    currentPage.value = 1; // 改变每页大小时重置当前页
    getlist()
};
const chaxun=()=>{
    currentPage.value=1;
    pageSize.value=10
    getlist()
}
const chongzhi=()=>{
    username.value=""
    currentPage.value=1;
    pageSize.value=10
   
    getlist()
}
const getlist=async()=>{
    const res=await service.get("/api/sys/user/list",{
        params:{
           username:username.value,
            current:currentPage.value,
            size:pageSize.value
        }
    })
    console.log(res)
    userlist.value=res.data.records;
    total.value=res.data.total
}
const handleCurrentChange = (newPage) => {
    currentPage.value = newPage;
    getlist()
};

const addUser = () => {
 
    dialogTitle.value = '新增用户';
    form.id = null;
    form.username = '';
    form.nickName = '';
    form.phone = '';
    form.email = '';

    dialogVisible.value = true;
};

const editUser = (user) => {
    dialogTitle.value = '编辑用户';
    Object.assign(form, user);
    dialogVisible.value = true;
};

const deleteUser = (user) => {
    ElMessageBox.confirm(`确定要删除用户 ${user.username} 吗？`, '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
    }).then(() => {
        const index = users.value.indexOf(user);
        if (index !== -1) {
            users.value.splice(index, 1);
            ElMessage.success('删除成功！');
        }
    }).catch(() => {
        ElMessage.info('已取消删除');
    });
};

const submitForm = () => {
    formRef.value.validate(async(valid) => {
        if (valid) {
            if (form.id) {
                const res=await service.put("/api/sys/user",form)
       console.log(res)
         if(res.code == 200){
            getlist()
            ElMessage.success('编辑成功！');
         }
            } else {
         const res=await service.post("/api/sys/user",form)
       console.log(res)
         if(res.code == 200){
            getlist()
         }

                ElMessage.success('新增成功！');
            }
            dialogVisible.value = false;
        } else {
            console.log('表单验证失败');
            return false;
        }
    });
};

const handleAvatarSuccess = (response, file) => {
    form.avatar = 
    URL.createObjectURL(file.raw);
};

const beforeAvatarUpload = (file) => {
    const isJPG = file.type === 'image/jpeg';
    const isLt2M = file.size / 1024 / 1024 < 2;

    if (!isJPG) {
        ElMessage.error('上传头像图片只能是 JPG 格式!');
    }
    if (!isLt2M) {
        ElMessage.error('上传头像图片大小不能超过 2MB!');
    }
    return isJPG && isLt2M;
};

</script>

<style scoped>
.table{
    width: 100%;
    height: auto;
    padding: 10px;
    box-sizing: border-box;
    background: #fff;
}
.form{
    width: 100%;
    padding: 10px;
    box-sizing: border-box;
    background: #fff;
    margin-bottom: 10px;
}

.user-management-container {

    width: 100%;
    height: 100%;

}

.box-card {
    width: 80%;
    max-width: 800px;
    padding: 30px;
    border-radius: 10px;
    box-shadow: 0 4px 8px rgba(0, 0, 0, 0.1);
}

.title {
    text-align: center;
    margin-bottom: 20px;
    color: #303133;
}




.el-table {
    margin-top: 20px;
}

.el-pagination {
    margin-top: 20px;
    text-align: center;
}

.avatar-uploader .el-upload {
    border: 1px dashed #d9d9d9;
    border-radius: 6px;
    cursor: pointer;
    position: relative;
    overflow: hidden;
}

.avatar-uploader .el-upload:hover {
    border-color: #409EFF;
}

.avatar-uploader-icon {
    font-size: 28px;
    color: #8c939d;
    width: 150px;
    height: 150px;
    line-height: 150px;
    text-align: center;
}

.avatar {
    width: 150px;
    height: 150px;
    display: block;
}
</style>